﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Data.SqlClient;
using BaseObject.Logic.BackMangage;
using DevExpress.Xpo;
using BaseClassUse.PObject.MPManage;

namespace JFLERP.IQ
{
    public partial class frmPEVSPOForSAP : DevExpress.XtraEditors.XtraForm, IMdiChildActions
    {


        public SAP_MM_P AccessType { get; set; }



        public frmPEVSPOForSAP()
        {
            InitializeComponent();


        }

        #region IMdiChildActions 成员

        public void Save()
        {

        }

        public void New()
        {

        }

        public void Delete()
        {

        }

        public void Print()
        {

        }

        public void SelectAll()
        {

        }

        public void Find()
        {

        }

        public void Export()
        {

        }

        #endregion



        private void GetDataFromSystem(SAP_MM_P StepNumber)
        {

            try
            {
                StringBuilder sbSql = new StringBuilder();
                sbSql.AppendFormat(" exec  sp_Get_MaterialOrderList @Materials='{0}',@BICode='{1}'", txt_MaterialNumber.Text,txt_BIReportName.Text);
                System.Data.DataTable dt = DbHelperSQL.Query(sbSql.ToString()).Tables[0];
                this.gdc_MpsMain.DataSource = dt;
                if (dt.Rows.Count > 0)
                {
                    txtFileName.Text = dt.Rows[0]["BIName"].ToString() + ".xlsx";
                    txt_BIReportName.Text = dt.Rows[0]["BIName"].ToString();
                }
                this.Text = "工艺与采购订单信息交流平台[" + dt.Rows.Count.ToString() + "]条记录.";
            }
            catch (Exception ex)
            {


            }

          
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.GetDataFromSystem(SAP_MM_P.ALL);

        }

        public enum SAP_MM_P
        {
            NONE,
            PO,
            PE,
            ALL,
            PL,
            GC,
            SAPUpload,
            ADMIN,
            PM
        }


        private void gdv_MpsMain_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            CFunctionUtility.DevCustomDrawRowIndicator(e, this.gdv_MpsMain);
        }

        private void gdv_MpsMain_KeyDown(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyDown(e, out boolCopy);
        }
        bool boolCopy = false;
        private void gdv_MpsMain_KeyUp(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyUp(e, this.gdv_MpsMain, out boolCopy);
        }

        private void frmStatusMonitor_JobMatReq_Load(object sender, EventArgs e)
        {
            CFunctionUtility.InitGridViewSetColumnReadOnly(this.gdv_MpsMain, true);


            if (CFunctionUtility.IsSysAdmin()||this.AccessType== SAP_MM_P.PE)
            {
                this.bandedGridColumn_del.Visible = true;
                this.bandedGridColumn_del.OptionsColumn.AllowEdit = true;

            }
            else
            {
                this.bandedGridColumn_del.Visible = false;
            }



            foreach (DevExpress.XtraGrid.Views.BandedGrid.BandedGridColumn item in this.gdv_MpsMain.Columns)
            {
                item.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            }

            foreach (DevExpress.XtraGrid.Views.BandedGrid.GridBand item in this.gdv_MpsMain.Bands)
            {
                item.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            }

            if (this.AccessType == SAP_MM_P.PE)
            {
                txtUpload_GY.Enabled = true;
            }
            else
            {
                txtUpload_GY.Enabled = false;
            }

            if (CFunctionUtility.IsSysAdmin())
            {
                txtUpload_GY.Enabled = true;
            }

            txtUserName.Text = Commoner.UseName.Trim();

            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "LCVSSAP", "E->F", Color.Yellow, false);
            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "MonitoredFlag", "N", Color.Yellow, false);
            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "Plant_spmatl_status", "ZE", Color.Red, false);

            ///不是管理员不显示
            if (!CFunctionUtility.IsSysAdmin())
            {
                this.txtUserName.Visible = false;
            }
            else
            {
                this.txtUserName.Visible = true;
            }
        }
  
        List<SAP_MaterialOrderList> LstSAPUploadList = new List<SAP_MaterialOrderList>();
       
        private void gdv_MpsMain_CustomDrawRowIndicator_1(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            CFunctionUtility.DevCustomDrawRowIndicator(e, this.gdv_MpsMain);
        }

        private void gdv_MpsMain_KeyDown_1(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyDown(e, out boolCopy);
        }

        private void gdv_MpsMain_KeyUp_1(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyUp(e, this.gdv_MpsMain, out boolCopy);
        }

        private void gdv_MpsMain_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            DataRow dr = gdv_MpsMain.GetDataRow(e.RowHandle);
            // if (e.Column.FieldName == "ProductionQty")
            //{
            //    if (decimal.Parse(dr["OrderQty"].ToString()) == decimal.Parse(dr["ProductionQty"].ToString()))
            //    {
            //        e.Appearance.BackColor = Color.YellowGreen;
            //    }
            //}
            // if (e.Column.FieldName == "DeliveriedQty")
            // {
            //     if (decimal.Parse(dr["OrderQty"].ToString()) == decimal.Parse(dr["DeliveriedQty"].ToString()))
            //     {
            //         e.Appearance.BackColor = Color.YellowGreen;
            //     }
            // }
        }

        private void chkIsShowOperator_CheckedChanged(object sender, EventArgs e)
        {

            foreach (DevExpress.XtraGrid.Columns.GridColumn item in gdv_MpsMain.Columns)
            {

            }

        }

        private void txtItemCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtTopLevelMaterial.Text))
            {
                MessageBox.Show("请填写顶层物料号码或者项目名称", "请填写顶层物料号码或者项目名称", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
       
            txtPath.Text = opf.FileName;

            DOUploadMaterialOrderList();

        }


        private void DOUploadMaterialOrderList()
        {
            StringBuilder sb_WorkOrder = new StringBuilder();
            LstSAPUploadList.Clear();
            try
            {

                if (!string.IsNullOrEmpty(txtPath.Text))
                {
                    System.Data.DataTable dt_excel = CFunctionUtility.LoadDataFromExcelForDataTable(txtPath.Text);

                    List<string> LstSQL = new List<string>();
                    for (int i = 0; i < dt_excel.Rows.Count; i++)
                    {
                        string _Explosion_level = dt_excel.Rows[i][0].ToString();
                        string _Item_Number = dt_excel.Rows[i][1].ToString();
                        string _Item_category = dt_excel.Rows[i][2].ToString();
                        string _Component_number = dt_excel.Rows[i][3].ToString();
                        string _Object_description = dt_excel.Rows[i][4].ToString();
                        string _Item_text_line_2 = dt_excel.Rows[i][5].ToString();
                        string _Doc_Version = dt_excel.Rows[i][6].ToString();
                        string _Comp_Qty_CUn = dt_excel.Rows[i][7].ToString();
                        string _Component_unit = dt_excel.Rows[i][8].ToString();
                        string _X_plant_matl_status = dt_excel.Rows[i][9].ToString();
                        string _Plant_spmatl_status = dt_excel.Rows[i][10].ToString();
                        string _Relevancy_to_Costing_Indicator = dt_excel.Rows[i][11].ToString();
                        string _Plnd_delivery_time = dt_excel.Rows[i][12].ToString();
                        string _Procurement_type = dt_excel.Rows[i][13].ToString();
                        string _Tot_repl_lead_time = dt_excel.Rows[i][14].ToString();
                        string _Document = dt_excel.Rows[i][15].ToString();
                        string _Document_version = dt_excel.Rows[i][16].ToString();
                        string _Document_2 = dt_excel.Rows[i][17].ToString();
                        string _Document_Type = dt_excel.Rows[i][18].ToString();
                        string _Document_type_2 = dt_excel.Rows[i][19].ToString();
                        string _Standard_price = dt_excel.Rows[i][20].ToString();


                        if (!string.IsNullOrEmpty(_Item_Number))
                        {
                            LstSAPUploadList.Add(new SAP_MaterialOrderList
                            {
                                Explosion_level = _Explosion_level,
                                Item_Number = _Item_Number,
                                Item_category = _Item_category,
                                Component_number = _Component_number,
                                Object_description = _Object_description,
                                Item_text_line_2 = _Item_text_line_2,
                                Doc_Version = _Doc_Version,
                                Comp_Qty_CUn = _Comp_Qty_CUn,
                                Component_unit = _Component_unit,
                                X_plant_matl_status = _X_plant_matl_status,
                                Plant_spmatl_status = _Plant_spmatl_status,
                                Relevancy_to_Costing_Indicator = _Relevancy_to_Costing_Indicator,
                                Plnd_delivery_time = _Plnd_delivery_time,
                                Procurement_type = _Procurement_type,
                                Tot_repl_lead_time = _Tot_repl_lead_time,
                                Document = _Document,
                                Document_version = _Document_version,
                                Document_2 = _Document_2,
                                Document_Type = _Document_Type,
                                Document_type_2 = _Document_type_2,
                                Standard_price = _Standard_price,
                                Creator = txtUserName.Text
                            });

                        }
                    }
                }

                this.gdc_MpsMain.RefreshDataSource();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                List<string> LstSQL = new List<string>();
                if (MessageBox.Show("确定要进行上传数据吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {


                    if (LstSAPUploadList.Count > 0)
                    {
                        StringBuilder sbm = new StringBuilder();
                        using (Session session = new Session(clsGetInstanceDataLayer.getInstance().getIDataLayer()))
                        {

                            session.ExplicitCommitTransaction();
                            foreach (SAP_MaterialOrderList item in LstSAPUploadList)
                            {
                                StringBuilder sbSql = new StringBuilder();
                                sbSql.Append("EXEC sp_Upload_MaterialOrderData ");
                                sbSql.AppendFormat("@Explosion_level ='{0}', ", item.Explosion_level);
                                sbSql.AppendFormat("@Item_Number ='{0}', ", item.Item_Number);
                                sbSql.AppendFormat("@Item_category ='{0}', ", item.Item_category);
                                sbSql.AppendFormat("@Component_number ='{0}', ", item.Component_number);
                                sbSql.AppendFormat("@Object_description ='{0}', ", item.Object_description);
                                sbSql.AppendFormat("@Item_text_line_2 ='{0}', ", item.Item_text_line_2);
                                sbSql.AppendFormat("@Doc_Version ='{0}', ", item.Doc_Version);
                                sbSql.AppendFormat("@Comp_Qty_CUn ='{0}', ", item.Comp_Qty_CUn);
                                sbSql.AppendFormat("@Component_unit ='{0}', ", item.Component_unit);
                                sbSql.AppendFormat("@X_plant_matl_status ='{0}', ", item.X_plant_matl_status);
                                sbSql.AppendFormat("@Plant_spmatl_status ='{0}', ", item.Plant_spmatl_status);
                                sbSql.AppendFormat("@Relevancy_to_Costing_Indicator ='{0}', ", item.Relevancy_to_Costing_Indicator);
                                sbSql.AppendFormat("@Plnd_delivery_time ='{0}', ", item.Plnd_delivery_time);
                                sbSql.AppendFormat("@Procurement_type ='{0}', ", item.Procurement_type);
                                sbSql.AppendFormat("@Tot_repl_lead_time ='{0}', ", item.Tot_repl_lead_time);
                                sbSql.AppendFormat("@Document ='{0}', ", item.Document);
                                sbSql.AppendFormat("@Document_version ='{0}', ", item.Document_version);
                                sbSql.AppendFormat("@Document_2 ='{0}', ", item.Document_2);
                                sbSql.AppendFormat("@Document_Type ='{0}', ", item.Document_Type);
                                sbSql.AppendFormat("@Document_type_2 ='{0}', ", item.Document_type_2);
                                sbSql.AppendFormat("@Standard_price ='{0}', ", item.Standard_price);
                                sbSql.AppendFormat("@Creator ='{0}', ", item.Creator);
                                sbSql.AppendFormat("@Oid ='{0}', ", item.Oid);
                                sbSql.AppendFormat("@MasteItemCode ='{0}'", txtTopLevelMaterial.Text);

                                LstSQL.Add(sbSql.ToString());

                            }

                            txt_MaterialNumber.Text = txtTopLevelMaterial.Text;
                            DbHelperSQL.ExecuteSqlTran(LstSQL);
                            MessageBox.Show("上传完毕，请核实!");
                        }
                    }
                }

                this.GetDataFromSystem(SAP_MM_P.ALL);
            }
        }


 

      

        private void btnPO_Click(object sender, EventArgs e)
        {
            this.GetDataFromSystem(SAP_MM_P.PO);
        }

        private void btnPlanning_Click(object sender, EventArgs e)
        {
            this.GetDataFromSystem(SAP_MM_P.PL);
        }

        private void xtraTabPage1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void repositoryItemSpinEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

        }

        private void repositoryItemButtonEdit_Delete_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DataRow dr = this.gdv_MpsMain.GetFocusedDataRow();
            if (dr != null)
            {
                string s = dr["MasteItemCode"].ToString();
                if (MessageBox.Show(string.Format("确定【{0}】吗?",s), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {

                    StringBuilder sbSql = new StringBuilder();
                    sbSql.Append("UPDATE sm SET sm.ActiveStatus='X' ");
                    sbSql.Append(",Del_Date=GETDATE() ");
                    sbSql.AppendFormat(" FROM SAP_MATERIALORDERLIST sm WHERE sm.MasteItemCode='{0}' ", dr["MasteItemCode"].ToString());
                    DbHelperSQL.ExecuteSql(sbSql.ToString());
                    MessageBox.Show("处理完毕", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.GetDataFromSystem(SAP_MM_P.ALL);
                }
            }
        }

        private void txtFileName_TextChanged(object sender, EventArgs e)
        {

        }

       

      

        private void btn_ExtendFinished_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            
        }

        /// <summary>
        /// 获得模板SN
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public string GetSNByType(string typeName)
        {
            StringBuilder sbSql_sn = new StringBuilder();
            sbSql_sn.Append("SELECT top 1   z.SN  FROM SAP_Template_Version z ");
            sbSql_sn.AppendFormat("WHERE z.TypeName='{0}' ", typeName);
            return DbHelperSQL.Query(sbSql_sn.ToString()).Tables[0].Rows[0]["SN"].ToString();
        }

        private void InitWCGLookupList()
        {

            StringBuilder sbSql = new StringBuilder();
            sbSql.Append("SELECT sph.[GROUP], sph.Main_Group, sph.Subgroup, sph.Prod_Hierarchy, ");
            sbSql.Append("       sph.Prod_Hierarchy_Code ");
            sbSql.Append("  FROM SAP_ProductHierarchy sph ");
            sbSql.Append("ORDER BY  sph.Prod_Hierarchy_Code ");

            DataSet dstemp = DbHelperSQL.Query(sbSql.ToString());

            if (dstemp != null && dstemp.Tables.Count > 0)
            {


                this.repositoryItemLookUpEdit_PrdHrchy.DataSource = dstemp.Tables[0];
                this.repositoryItemLookUpEdit_PrdHrchy.DisplayMember = "Prod_Hierarchy";
                this.repositoryItemLookUpEdit_PrdHrchy.ValueMember = "Prod_Hierarchy_Code";


            }

        }

        private void repositoryItemButtonEdit_ProHrchySave_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DataRow dr = this.gdv_MpsMain.GetFocusedDataRow();
            if (dr != null)
            {
                string strProductHierarchy = dr["ProductHierarchy"].ToString();
                if (SaveProductHierarchy(dr["Material_Number"].ToString(), strProductHierarchy))
                {
                    dr["EditStatus"] = "Y";
                    this.gdc_MpsMain.RefreshDataSource();
                }
            }
        }

        private bool SaveProductHierarchy(string Material_Number, string ProductHierarchy)
        {
            StringBuilder sbSql = new StringBuilder();
            sbSql.AppendFormat(" UPDATE sim SET sim.ProductHierarchy = '{0}' ,", ProductHierarchy);
            sbSql.AppendFormat(" GC_P_User='{0}',", txtUserName.Text);
            sbSql.AppendFormat(" GC_P_Date=case  when GC_P_Date IS NULL then  getdate() else GC_P_Date end");
            sbSql.AppendFormat(" FROM SAP_ItemMaster sim WHERE sim.Material_Number='{0}' ", Material_Number);
            return DbHelperSQL.ExecuteSql(sbSql.ToString()) > 0;
        }

        private void 导入ViewResultToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtPath.Text = opf.FileName;
          
        }

 
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            this.GetDataFromSystem(SAP_MM_P.SAPUpload);
        }

  

        private void btn_TableToList_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            List<string> Lst_Component = new List<string>();


            if ((this.gdc_MpsMain.DataSource as System.Data.DataTable) != null)
            {
                foreach (DataRow dr in (this.gdc_MpsMain.DataSource as System.Data.DataTable).Rows)
                {
                    string s = dr["Component_number"].ToString().Trim();
                    if (!Lst_Component.Exists(p => p == s))
                    {
                        Lst_Component.Add(s);
                        sb.AppendFormat("{0}{1}", dr["Component_number"].ToString(), System.Environment.NewLine);
                    }
                }
            }
            rch_MaterialList.Text = "";
            rch_MaterialList.AppendText(sb.ToString());
            this.AppendMessage(string.Format("物料数量【{0}】", Lst_Component.Count));
           
        }

        private void rch_MaterialList_DoubleClick(object sender, EventArgs e)
        {
            rch_MaterialList.SelectAll();
        }

        private void AppendMessage(string msg)
        {
            this.rch_Message.AppendText(msg + System.Environment.NewLine);
        }

        private void rch_Message_DoubleClick(object sender, EventArgs e)
        {
            rch_Message.SelectAll();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            CFunctionUtility.ExportToExcel(this.gdv_MpsMain,txtFileName.Text);
        }

        private void txt_MaterialNumber_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            
        }

        private void txt_BIReportName_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmPVSelect newform = new frmPVSelect();
            newform.TFormName = "BI Report List";
            newform.TstrTable = "SAP_BIReportName"; // "cv_YearMonth"; 
            newform.TSelFields = "BICode,代码;BIName,报表名称;RecordQty,记录数;Owner,归属人";
            newform.TOrderBY = " Order  by BIName";
            newform.TSpecialWhere = " and FunctionName='CS12'"; // " And Year*100+Month>=2014*100+11 ";
            newform.Width = 550;
            newform.Height = 700;

            newform.ShowDialog();

            if (newform.TDataRow != null)
            {

                txt_BIReportName.Text = newform.TDataRow["BICode"].ToString();

            }
        }

        private void txt_BIReportName_DoubleClick(object sender, EventArgs e)
        {
            txt_BIReportName.Text = "";
        }
   
 

    }

    public class SAP_MaterialOrderList
    {

        public string Explosion_level { set; get; }
        public string Item_Number { set; get; }
        public string Item_category { set; get; }
        public string Component_number { set; get; }
        public string Object_description { set; get; }
        public string Item_text_line_2 { set; get; }
        public string Doc_Version { set; get; }
        public string Comp_Qty_CUn { set; get; }
        public string Component_unit { set; get; }
        public string X_plant_matl_status { set; get; }
        public string Plant_spmatl_status { set; get; }
        public string Relevancy_to_Costing_Indicator { set; get; }
        public string Plnd_delivery_time { set; get; }
        public string Procurement_type { set; get; }
        public string Tot_repl_lead_time { set; get; }
        public string Document { set; get; }
        public string Document_version { set; get; }
        public string Document_2 { set; get; }
        public string Document_Type { set; get; }
        public string Document_type_2 { set; get; }
        public string Standard_price { set; get; }
        public string Creator { set; get; }
        public string Oid { set; get; }


    }

 

}